<?php

namespace App\Traits;

use App\Models\AdminLog;

trait LogsActivity
{
    /**
     * 记录操作日志
     */
    protected function logActivity(
        string $action,
        string $module,
        string $description,
        $model = null,
        ?array $oldData = null,
        ?array $newData = null
    ): void {
        AdminLog::record(
            action: $action,
            module: $module,
            description: $description,
            modelType: $model ? get_class($model) : null,
            modelId: $model?->id ?? null,
            oldData: $oldData,
            newData: $newData
        );
    }

    /**
     * 记录创建操作
     */
    protected function logCreate(string $module, string $itemName, $model = null): void
    {
        $this->logActivity(
            action: 'create',
            module: $module,
            description: "创建{$this->getModuleName($module)}: {$itemName}",
            model: $model
        );
    }

    /**
     * 记录更新操作
     */
    protected function logUpdate(string $module, string $itemName, $model = null, ?array $oldData = null, ?array $newData = null): void
    {
        $this->logActivity(
            action: 'update',
            module: $module,
            description: "更新{$this->getModuleName($module)}: {$itemName}",
            model: $model,
            oldData: $oldData,
            newData: $newData
        );
    }

    /**
     * 记录删除操作
     */
    protected function logDelete(string $module, string $itemName, $model = null): void
    {
        $this->logActivity(
            action: 'delete',
            module: $module,
            description: "删除{$this->getModuleName($module)}: {$itemName}",
            model: $model
        );
    }

    /**
     * 记录状态切换操作
     */
    protected function logToggleStatus(string $module, string $itemName, string $status, $model = null): void
    {
        $this->logActivity(
            action: 'update',
            module: $module,
            description: "切换{$this->getModuleName($module)}状态: {$itemName} -> {$status}",
            model: $model
        );
    }

    /**
     * 记录订单状态变更
     */
    protected function logOrderStatusChange(string $orderNumber, string $oldStatus, string $newStatus, $model = null): void
    {
        $this->logActivity(
            action: 'update',
            module: 'orders',
            description: "订单状态变更: {$orderNumber} ({$oldStatus} -> {$newStatus})",
            model: $model,
            oldData: ['status' => $oldStatus],
            newData: ['status' => $newStatus]
        );
    }

    /**
     * 获取模块名称
     */
    private function getModuleName(string $module): string
    {
        return match($module) {
            'products' => '产品',
            'orders' => '订单',
            'users' => '用户',
            'categories' => '分类',
            'system-settings' => '系统设置',
            'specification-templates' => '规格模板',
            'variants' => '产品变体',
            default => $module,
        };
    }
}

